<template>
  <div class="dashboard-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <h1 class="logo">校园智慧竞赛平台 - 管理后台</h1>
      </div>
      <div class="header-right">
        <span class="admin-name">{{ adminName }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <nav class="nav-menu">
          <div class="menu-item" @click="navigateTo('/dashboard')">
            <i class="icon">📊</i>
            <span>仪表盘</span>
          </div>
          <div class="menu-item active">
            <i class="icon">👥</i>
            <span>用户审核</span>
          </div>
          <div class="menu-item" @click="navigateTo('/user-management')">
            <i class="icon">👤</i>
            <span>用户管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/team-management')">
            <i class="icon">⚡</i>
            <span>队伍管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/homepage-editor')">
            <i class="icon">🏠</i>
            <span>主页编辑</span>
          </div>
          <div class="menu-item" @click="navigateTo('/system-notifications')">
            <i class="icon">📢</i>
            <span>通知管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/news-management')">
            <i class="icon">📰</i>
            <span>新闻管理</span>
          </div>
        <div class="menu-item" @click="navigateTo('/event-management')">
          <i class="icon">🏆</i>
          <span>赛事管理</span>
        </div>
        </nav>
      </aside>

      <!-- 主要内容区域 -->
      <main class="content">
        <div class="page-header">
          <h2>用户审核</h2>
          <div class="header-actions">
            <div class="filter-tabs">
              <button
                class="tab-btn"
                :class="{ active: currentTab === 'all' }"
                @click="switchTab('all')"
              >
                全部 ({{ allUsers.length }})
              </button>
              <button
                class="tab-btn"
                :class="{ active: currentTab === 'student' }"
                @click="switchTab('student')"
              >
                学生 ({{ studentUsers.length }})
              </button>
              <button
                class="tab-btn"
                :class="{ active: currentTab === 'teacher' }"
                @click="switchTab('teacher')"
              >
                教师 ({{ teacherUsers.length }})
              </button>
            </div>
            <div class="export-actions">
              <button 
                class="export-btn"
                :class="{ loading: isExporting }"
                @click="handleExportPending"
                :disabled="isExporting"
              >
                <span v-if="isExporting">导出中...</span>
                <span v-else>📊 导出待审核数据</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 批量操作栏 -->
        <div class="batch-actions" v-if="selectedUsers.length > 0">
          <div class="batch-info">
            已选择 {{ selectedUsers.length }} 个用户
          </div>
          <div class="batch-buttons">
            <button class="batch-approve-btn" @click="handleBatchApprove">
              批量通过
            </button>
            <button class="batch-reject-btn" @click="handleBatchReject">
              批量驳回
            </button>
            <button class="batch-clear-btn" @click="clearSelection">
              清除选择
            </button>
          </div>
        </div>

        <!-- 用户列表 -->
        <div class="user-list">
          <div v-if="loading" class="loading">
            加载中...
          </div>
          
          <div v-else-if="currentUsers.length === 0" class="empty-state">
            <div class="empty-icon">📝</div>
            <p>暂无待审核用户</p>
          </div>
          
          <div v-else class="user-table-container">
            <table class="user-table">
              <thead>
                <tr>
                  <th>选择</th>
                  <th>姓名</th>
                  <th>身份</th>
                  <th>学号/工号</th>
                  <th>学院/职位</th>
                  <th>申请时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="user in paginatedUsers"
                  :key="user.id"
                  class="user-row"
                  :class="{ selected: selectedUsers.includes(user.id) }"
                >
                  <td>
                    <input
                      type="checkbox"
                      :checked="selectedUsers.includes(user.id)"
                      @change="toggleUserSelection(user.id)"
                    />
                  </td>
                  <td class="user-name">{{ user.realName || '未填写' }}</td>
                  <td class="user-type">{{ user.userTypeName || (user.userType === 2 ? '学生' : '教师') }}</td>
                  <td class="user-id">{{ user.loginId }}</td>
                  <td class="user-extra">
                    <!-- 学生显示学院，教师显示职位 -->
                    <span v-if="user.userType === 2">{{ user.college || '未填写' }}</span>
                    <span v-else>{{ user.professionalTitle || '未填写' }}</span>
                  </td>
                  <td class="apply-time">{{ formatTime(user.createTime) }}</td>
                  <td class="user-actions">
                    <button
                      class="approve-btn"
                      @click="handleApprove(user)"
                      :disabled="processing"
                    >
                      通过
                    </button>
                    <button
                      class="reject-btn"
                      @click="handleReject(user)"
                      :disabled="processing"
                    >
                      驳回
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="pagination" v-if="totalPages > 1">
            <button
              class="page-btn"
              :disabled="currentPage === 1"
              @click="changePage(currentPage - 1)"
            >
              上一页
            </button>
            <div class="page-numbers">
              <button
                v-for="page in visiblePages"
                :key="page"
                class="page-number"
                :class="{ active: page === currentPage }"
                @click="changePage(page)"
              >
                {{ page }}
              </button>
            </div>
            <button
              class="page-btn"
              :disabled="currentPage === totalPages"
              @click="changePage(currentPage + 1)"
            >
              下一页
            </button>
            <div class="page-info">
              共 {{ currentUsers.length }} 条，第 {{ currentPage }} / {{ totalPages }} 页
            </div>
          </div>
        </div>
      </main>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="closeConfirmModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ confirmModal.title }}</h3>
          <button class="close-btn" @click="closeConfirmModal">×</button>
        </div>
        <div class="modal-body">
          <p>{{ confirmModal.message }}</p>
          <div v-if="confirmModal.type === 'reject' || confirmModal.type === 'batch-reject'" class="reject-reason">
            <label>驳回原因：</label>
            <textarea
              v-model="rejectReason"
              placeholder="请输入驳回原因（可选）"
              rows="3"
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeConfirmModal">取消</button>
          <button 
            class="confirm-btn" 
            :class="confirmModal.type" 
            @click="confirmAction"
            :disabled="processing"
          >
            {{ processing ? '处理中...' : '确定' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="showMessage" class="message-toast" :class="messageType">
      {{ messageText }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import { getPendingUsersService, auditUserService, exportPendingUsersService } from '@/api/admin.js'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 数据状态
const loading = ref(false)
const processing = ref(false)
const currentTab = ref('all')
const allUsers = ref([])
const studentUsers = ref([])
const teacherUsers = ref([])
const selectedUsers = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = 10

// 当前显示的用户列表
const currentUsers = computed(() => {
  switch (currentTab.value) {
    case 'student':
      return studentUsers.value
    case 'teacher':
      return teacherUsers.value
    default:
      return allUsers.value
  }
})

// 分页后的用户列表
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return currentUsers.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(currentUsers.value.length / pageSize)
})

// 可见的页码
const visiblePages = computed(() => {
  const total = totalPages.value
  const current = currentPage.value
  const pages = []

  if (total <= 7) {
    // 如果总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 否则显示当前页前后各2页
    const start = Math.max(1, current - 2)
    const end = Math.min(total, current + 2)

    for (let i = start; i <= end; i++) {
      pages.push(i)
    }
  }

  return pages
})

// 确认弹窗
const showConfirmModal = ref(false)
const confirmModal = ref({
  title: '',
  message: '',
  type: '',
  user: null
})
const rejectReason = ref('')

// 消息提示
const showMessage = ref(false)
const messageText = ref('')
const messageType = ref('success')

// 导出状态
const isExporting = ref(false)

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 切换标签页
const switchTab = (tab) => {
  currentTab.value = tab
  selectedUsers.value = [] // 清除选择
  currentPage.value = 1 // 重置到第一页
}

// 切换页面
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}



// 切换用户选择
const toggleUserSelection = (userId) => {
  const index = selectedUsers.value.indexOf(userId)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(userId)
  }
}

// 清除选择
const clearSelection = () => {
  selectedUsers.value = []
}

// 批量通过
const handleBatchApprove = () => {
  if (selectedUsers.value.length === 0) return

  confirmModal.value = {
    title: '批量审核通过',
    message: `确定要通过选中的 ${selectedUsers.value.length} 个用户的注册申请吗？`,
    type: 'batch-approve',
    users: selectedUsers.value
  }
  showConfirmModal.value = true
}

// 批量驳回
const handleBatchReject = () => {
  if (selectedUsers.value.length === 0) return

  confirmModal.value = {
    title: '批量审核驳回',
    message: `确定要驳回选中的 ${selectedUsers.value.length} 个用户的注册申请吗？\n⚠️ 驳回后这些用户账号将被禁用，无法登录系统。`,
    type: 'batch-reject',
    users: selectedUsers.value
  }
  rejectReason.value = ''
  showConfirmModal.value = true
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '未知'
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

// 显示消息
const showMessageToast = (text, type = 'success') => {
  messageText.value = text
  messageType.value = type
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 3000)
}

// 加载待审核用户
const loadPendingUsers = async () => {
  loading.value = true
  try {
    // 根据当前标签页决定用户类型参数
    let userTypeParam = ''
    if (currentTab.value === 'student') {
      userTypeParam = '2' // 学生
    } else if (currentTab.value === 'teacher') {
      userTypeParam = '1' // 教师
    }

    const result = await getPendingUsersService(userTypeParam)
    if (result.code === 200) {
      let users = result.data || []

      allUsers.value = users
      studentUsers.value = users.filter(user => user.userType === 2) // 2表示学生
      teacherUsers.value = users.filter(user => user.userType === 1) // 1表示教师
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    showMessageToast('加载用户列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 处理审核通过
const handleApprove = (user) => {
  confirmModal.value = {
    title: '确认通过',
    message: `确定要通过 ${user.realName || user.loginId} 的注册申请吗？`,
    type: 'approve',
    user: user
  }
  showConfirmModal.value = true
}

// 处理审核驳回
const handleReject = (user) => {
  confirmModal.value = {
    title: '确认驳回',
    message: `确定要驳回 ${user.realName || user.loginId} 的注册申请吗？\n⚠️ 驳回后该用户账号将被禁用，无法登录系统。`,
    type: 'reject',
    user: user
  }
  rejectReason.value = ''
  showConfirmModal.value = true
}



// 确认操作
const confirmAction = async () => {
  processing.value = true
  try {
    const { type, user, users } = confirmModal.value

    if (type === 'approve' || type === 'reject') {
      const auditData = {
        userId: user.id,
        userType: user.userType, // 直接使用数字格式：1-教师，2-学生
        auditStatus: type === 'approve' ? 1 : 2, // 1-通过，2-驳回
      }

      // 只有驳回时才添加驳回原因
      if (type === 'reject' && rejectReason.value) {
        auditData.auditReason = rejectReason.value
      }

      console.log('发送审核数据:', auditData) // 调试信息
      const result = await auditUserService(auditData)
      if (result.code === 200) {
        const successMessage = type === 'approve'
          ? '审核通过成功，用户可正常使用系统'
          : '审核驳回成功，用户账号已被禁用'
        showMessageToast(successMessage)
        await loadPendingUsers() // 重新加载列表
      } else {
        showMessageToast(result.message || '操作失败', 'error')
      }
    } else if (type === 'batch-approve' || type === 'batch-reject') {
      // 批量操作
      const auditStatus = type === 'batch-approve' ? 1 : 2
      const auditReason = type === 'batch-reject' ? rejectReason.value : undefined

      let successCount = 0
      let failCount = 0

      for (const userId of users) {
        try {
          const targetUser = currentUsers.value.find(u => u.id === userId)
          if (targetUser) {
            const auditData = {
              userId: targetUser.id,
              userType: targetUser.userType, // 直接使用数字格式：1-教师，2-学生
              auditStatus
            }

            // 只有驳回时才添加驳回原因
            if (auditStatus === 2 && auditReason) {
              auditData.auditReason = auditReason
            }

            const result = await auditUserService(auditData)
            if (result.code === 200) {
              successCount++
            } else {
              failCount++
            }
          }
        } catch (error) {
          failCount++
        }
      }

      if (successCount > 0) {
        const operationType = type === 'batch-approve' ? '通过' : '驳回'
        const statusNote = type === 'batch-approve' ? '，用户可正常使用系统' : '，用户账号已被禁用'
        showMessageToast(`批量${operationType}完成：成功 ${successCount} 个，失败 ${failCount} 个${statusNote}`)
      } else {
        showMessageToast('批量操作失败', 'error')
      }

      selectedUsers.value = [] // 清除选择
      await loadPendingUsers() // 重新加载列表
    }

    closeConfirmModal()
  } catch (error) {
    console.error('操作失败:', error)
    showMessageToast('操作失败，请稍后重试', 'error')
  } finally {
    processing.value = false
  }
}

// 关闭确认弹窗
const closeConfirmModal = () => {
  showConfirmModal.value = false
  rejectReason.value = ''
}

// 处理文件下载
const handleFileDownload = (blob, filename) => {
  try {
    // 检查响应是否为空
    if (!blob || blob.size === 0) {
      throw new Error('导出的文件为空')
    }
    
    // 检查响应类型
    const contentType = blob.type
    if (!contentType.includes('spreadsheetml.sheet') && !contentType.includes('ms-excel')) {
      throw new Error('导出的文件格式不正确')
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    
    // 清理资源
    window.URL.revokeObjectURL(url)
    document.body.removeChild(link)
    
    return true
  } catch (error) {
    console.error('文件下载失败:', error)
    throw error
  }
}

// 导出待审核用户数据
const handleExportPending = async () => {
  if (isExporting.value) return
  
  isExporting.value = true
  try {
    showMessageToast('正在导出数据，请稍候...')
    
    const response = await exportPendingUsersService()
    
    // 处理文件下载
    const filename = `待审核用户数据_${new Date().toLocaleDateString()}.xlsx`
    handleFileDownload(response, filename)
    
    showMessageToast('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    showMessageToast(error.message || '导出失败，请重试', 'error')
  } finally {
    isExporting.value = false
  }
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadPendingUsers()
})
</script>

<style scoped>
@import '@/assets/css/UserAudit.css';

/* 导出按钮样式 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
  width: 100%;
}

.filter-tabs {
  display: flex;
  gap: 8px;
  flex: 1;
}

.export-actions {
  flex-shrink: 0;
}

.export-btn {
  background: #52c41a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 140px;
  justify-content: center;
}

.export-btn:hover:not(:disabled) {
  background: #73d13d;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.export-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.export-btn.loading {
  background: #faad14;
}

.export-btn.loading:hover {
  background: #ffc53d;
}
</style>
